package LiKou;

import java.util.Stack;

public class Test2 {
    public static void main(String[] args) {
        String s= ")(((((()())()()))()(()))(";
        System.out.println(longestValidParentheses(s));
    }
    public static int longestValidParentheses(String s) {
        int len=s.length();
        if(len==0){
            return 0;
        }
        int maxResult=0;
        Stack<Character> stack=new Stack<>();
        for(int i=0;i<len;i++){
            int count=0;
            if(s.charAt(i)==')' && stack.empty()){
                continue;
            }
            for(int j=i;j<len;j++){
                if(j==len-1 && stack.empty()){
                    break;
                }
                if(s.charAt(j)==')' && stack.empty()){
                    break;
                }
                if(s.charAt(j)==')' && !stack.empty()){
                    stack.pop();
                    count+=2;
                }
                if(s.charAt(j)=='('){
                    stack.add(s.charAt(j));
                }
                if(j==len-1 && !stack.empty()){
                    count-=stack.size()*2;
                }
            }
            if(count>maxResult){
                maxResult=count;
            }
        }
        return maxResult;
    }
}
